﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ww.wwf.wwfbll;
using ww.wwf.com;
using ww.form.Properties;
namespace ww.form.wwf
{
    public partial class LoginForm : Form
    {
        LoginBLL bll = new LoginBLL();
        DataTable dtorg = new DataTable();
        public LoginForm()
        {
            InitializeComponent();
          
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            FormInitSet();

            if (Settings.Default.IsAutoLogin)
            {
                this.SysLoginUserName.Text = Settings.Default.strLoingName;
                this.SysLoginPassword.Text = Settings.Default.strLoingPwd;
                SysLoginLogin_Click(null, null);
            }
        }
        /// <summary>
        /// 开始窗口设置
        /// </summary>
        void FormInitSet()
        {
            try
            {
                this.Width = 425;
                this.Height = 280;
                this.DataGridViewObject.Visible = false;
                this.SysLoginUserName.Text = Settings.Default.strLoingName;
                this.labelSysName.Text = LoginBLL.sysName;
                this.labelC.Text = LoginBLL.sysVar;
                this.label3.Text = LoginBLL.Copyright;
            }
            catch (Exception ex)
            {
                WWMessage.MessageShowError(ex.ToString());
            }
        }
        /// <summary>
        /// 登录确认
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SysLoginLogin_Click(object sender, EventArgs e)
        {
            try
            { 
                Cursor = Cursors.WaitCursor;
                LoginOK();
                SaveConfigSet();
                #region 注册判断
                DataTable dt_xt_reg = bll.Get_xt_reg();
                if (dt_xt_reg.Rows.Count > 0)//注册了，判断是否过期，及用户数的问题
                {
                    string str_code = dt_xt_reg.Rows[0]["reg"].ToString().Trim();
                    string str_yhmc = "";
                    string str_jzrq = "";
                    string str_yhsl = "";
                    string str_xtlx = "";
                    try
                    {
                        str_yhmc = dt_xt_reg.Rows[0]["dwmc"].ToString().Trim();
                        str_jzrq = dt_xt_reg.Rows[0]["jzrq"].ToString().Trim();
                        str_yhsl = dt_xt_reg.Rows[0]["yhsl"].ToString().Trim();
                        str_xtlx = "检验";

                        Program.sys_jzrq = Convert.ToDateTime(str_jzrq);
                    }
                    catch
                    {
                        MessageBox.Show("系统注册码异常，请联系供应商！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Program.sfzc = false;
                        Form_reg frm = new Form_reg();
                        frm.ShowDialog();
                        Application.Exit();
                    }
                    if (str_xtlx != "检验")
                    {
                        MessageBox.Show("系统注册码异常，请联系供应商！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Program.sfzc = false;
                        Application.Exit();
                    }
                    if (str_jzrq.Trim() == "")
                    {
                        MessageBox.Show("系统注册码异常，请联系供应商！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Program.sfzc = false;
                        Application.Exit();
                    }
                    if (str_yhsl == "") str_yhsl = "1";
                    //当用户数量大于的时候关闭应用程序
                    if (Convert.ToInt32(bll.Get_Yhsl()) > Convert.ToInt32(str_yhsl))
                    {
                        MessageBox.Show("系统超过许可数量，请联系供应商！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Program.sfzc = false;
                        Form_reg frm = new Form_reg();
                        frm.ShowDialog();
                        Application.Exit();
                    }
                    //没有过期的时候
                    if (Convert.ToDateTime(str_jzrq) < bll.GetServerDate())
                    {
                        Program.sfzc = false;
                        MessageBox.Show("系统已经到期，请联系供应商！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Form_reg frm = new Form_reg();
                        frm.ShowDialog();
                        Application.Exit();
                    }
                    else
                    {
                        Program.sfzc = true;
                        if (Convert.ToDateTime(str_jzrq) < bll.GetServerDate().AddDays(7))
                        {
                            MessageBox.Show("系统快要到期，为了不影响您的使用，请联系供应商！\n到期日期：" + str_jzrq, "提示",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }

                    if (LoginBLL.CustomerName != str_yhmc)//体检单位名称不一致
                    {
                        MessageBox.Show("系统注册码异常，请联系供应商！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Program.sfzc = false;
                        Form_reg frm = new Form_reg();
                        frm.ShowDialog();
                        Application.Exit();
                    }
                }
                else//没有注册
                {
                    MessageBox.Show("系统注册码异常，请联系供应商！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Program.sfzc = false;
                    Form_reg frm = new Form_reg();
                    frm.ShowDialog();
                    Application.Exit();
                }
                #endregion
                
            }
            catch (Exception ex)
            {
                ww.wwf.wwfbll.WWMessage.MessageShowError(ex.ToString());
            }
            finally
            {
                Cursor = Cursors.Arrow;
            }
        }
        /// <summary>
        /// 登录判断
        /// </summary>
        private void LoginOK()
        {           

            if (this.SysLoginUserName.Text == "" || SysLoginUserName.Text == null || SysLoginUserName.Text.Length == 0)
            {
                ww.wwf.wwfbll.WWMessage.MessageShowWarning("用户名不能为空！");
                return;
            }
            else
            {
                int intOrgcount = 0;
                string userid = this.SysLoginUserName.Text;
                string pwd = this.SysLoginPassword.Text;
                if (this.bll.BllUserPassOk(userid, pwd))
                {
                    dtorg = this.bll.BllUserOrg(userid);
                    intOrgcount = dtorg.Rows.Count;
                    if (dtorg.Rows.Count == 1)
                    {
                        ShowSysMain(dtorg.Rows[0]["forg_id"].ToString());
                    }
                    else if (intOrgcount > 1)
                    {
                        this.ActiveControl = this.DataGridViewObject;
                        DataGridViewObjectVisible();
                    }
                    else
                    {
                        ww.wwf.wwfbll.WWMessage.MessageShowWarning(this.SysLoginUserName.Text + " 未分配到部门、岗位，请联系管理员。");
                        return;
                    }
                }
                else
                {
                    ww.wwf.wwfbll.WWMessage.MessageShowWarning("用户名或密码有误！请重新输入");                    
                }

            }
        }
        /// <summary>
        /// 用户只在一个岗位时
        /// </summary>
        /// <param name="fperson_id"></param>
        private void ShowSysMain(string forg_id)
        {
            this.bll.BllSetLoginValue(dtorg, forg_id);
            this.DialogResult = DialogResult.OK;
        }

        /// <summary>
        /// 用户有多个岗位
        /// </summary>
        private void DataGridViewObjectVisible()
        {
            this.Width = 425;
            this.Height = 380;
            DataGridViewObject.Visible = true;
            this.DataGridViewObject.AutoGenerateColumns = false;
            this.DataGridViewObject.DataSource = dtorg;
        }

        /// <summary>
        /// 存储配置文件
        /// </summary>
        private void SaveConfigSet()
        {
            try
            {               
                Settings.Default.strLoingName = SysLoginUserName.Text;               
               
                Settings.Default.Save();                
            }
            catch (Exception ex)
            {
                WWMessage.MessageShowError(ex.ToString());
            }
        }
        /*
        /// <summary>
        /// 动态修改业务数据库连接
        /// </summary>
        private void UpdateAppConfig()
        {

            try
            {
                if ((textBoxTZ.Text.Trim() == System.Configuration.ConfigurationSettings.AppSettings["BusinessTZ"]) & (System.Configuration.ConfigurationSettings.AppSettings["BusinessYear"] == comboBoxYear.SelectedItem.ToString().Trim())) { }
                else
                {
                    //数据库名称
                    string strDBName = System.Configuration.ConfigurationSettings.AppSettings["BusinessInitialCatalog"] + "_" + textBoxTZ.Text + "_" + comboBoxYear.SelectedItem.ToString();
                    string strSysDBValue = "data source=" + System.Configuration.ConfigurationSettings.AppSettings["BusinessDataSource"] + ";Initial Catalog=" + strDBName + ";User ID=" + System.Configuration.ConfigurationSettings.AppSettings["BusinessUserID"] + ";Password=" + System.Configuration.ConfigurationSettings.AppSettings["BusinessPassword"] + ";Provider=SQLOLEDB.1;Persist Security Info=True;";
                    AppConfig.ConfigSetValue(System.Windows.Forms.Application.ExecutablePath, "WW.DBConn.Business", strSysDBValue);

                    AppConfig.ConfigSetValueAppSettings(System.Windows.Forms.Application.ExecutablePath, "BusinessTZ", textBoxTZ.Text.Trim());
                    AppConfig.ConfigSetValueAppSettings(System.Windows.Forms.Application.ExecutablePath, "BusinessYear", comboBoxYear.SelectedItem.ToString().Trim());


                    try
                    {
                        ww.wwf.wwfbll.WWMessage.MessageShowInformation("账套或年度已经改变，请重新启动后生效！");
                        Application.Exit();
                        //Application.Run(new MainForm());
                    }
                    catch (Exception ex)
                    {
                        ww.wwf.wwfbll.WWMessage.MessageShowError(ex.ToString());
                    }
                }

            }
            catch (Exception ex)
            {
                ww.wwf.wwfbll.WWMessage.MessageShowError(ex.ToString());
            }
        }*/
        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SysLoginCancel_Click(object sender, EventArgs e)
        {
            try
            {
               // SaveConfigSet();
               // this.Close();
                Application.Exit();
            }
            catch (Exception ex)
            {
                ww.wwf.wwfbll.WWMessage.MessageShowError(ex.ToString());
            }
        }
        
        private void DataGridViewObject_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                string orgid = this.DataGridViewObject.CurrentRow.Cells["forg_id"].Value.ToString();
                //MessageBox.Show(orgid);
                ShowSysMain(orgid);
            }
            catch (Exception ex)
            {
                ww.wwf.wwfbll.WWMessage.MessageShowError(ex.ToString());
            }
            finally
            {
                Cursor = Cursors.Arrow;
            }
        }

        private void SysLoginUserName_KeyDown(object sender, KeyEventArgs e)
        {
             if (e.KeyCode == Keys.Enter)
                 this.ActiveControl = SysLoginPassword;
        }

        private void SysLoginPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                this.ActiveControl = SysLoginLogin;
        }
      
        private void DataGridViewObject_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Space))//或(e.KeyCode==Keys.Enter) 
            {

                try
                {
                    Cursor = Cursors.WaitCursor;
                    string orgid = this.DataGridViewObject.CurrentRow.Cells["forg_id"].Value.ToString();
                    //MessageBox.Show(orgid);
                    ShowSysMain(orgid);
                }
                catch (Exception ex)
                {
                    ww.wwf.wwfbll.WWMessage.MessageShowError(ex.ToString());
                }
                finally
                {
                    Cursor = Cursors.Arrow;
                }
            }
        }

        private void buttonHelp_Click(object sender, EventArgs e)
        {
            try
            {
                AboutDialog aboutDialog = new AboutDialog();
                aboutDialog.ShowDialog(this);
                //MessageBox.Show(LoginBLL.strHelpContact, "服务 联系方式", MessageBoxButtons.OK, MessageBoxIcon.Question);
            }
            catch (Exception ex)
            {
                ww.wwf.wwfbll.WWMessage.MessageShowError(ex.ToString());
            }
        } 
    }
}